<template>
  <div class="img-contain">
    <draggable v-model="imgList" class="img-list" @end="drop(1)" draggable=".item">
      <div class="demo-upload-list " :class="hasDrag?'item':''" v-if="isboxUpload"
        v-for="(item, index) in imgList" :key="index+'-label'">
        <!--<div class="demo-upload-list-cover">-->
        <!--<div @click="viewPdf(item)" v-if="!/(gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)$/.test(item.suffixType)">-->
        <!--<Icon color="#ddd" type="search" title='查看附件'></Icon>-->
        <!--</div>-->
        <!--</div>-->
        <!--<img src="../assets/images/pdf.png" v-if="/(pdf|PDF)$/.test(item.suffixType)">-->
        <!--<img src="../assets/images/word.png" v-if="/(doc|DOC|docx|DOCX)$/.test(item.suffixType)">-->
        <!--<img src="../assets/images/zip.png" v-if="/(zip|ZIP)$/.test(item.suffixType)">-->
        <!--<img src="../assets/images/txt.png" v-if="/(txt|txt)$/.test(item.suffixType)">-->
        <!--<img src="../assets/images/xls.png" v-if="/(xls|xlsx|XLS|XLSX)$/.test(item.suffixType)">-->
        <!--<img src="../assets/images/ppt.png" v-if="/(ppt|PPT)$/.test(item.suffixType)">-->
        <img :src="item.annexPath" class="img">
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline" title="预览" @click.native="onPreview(index)"></Icon>
          <Icon type="ios-trash-outline" v-if="mark" title="删除"
            @click.native="handleRemove(index, item)"></Icon>
        </div>
        <div class="list-cover-marker" v-if="hasCover" @click="handleSetCover(index, item)"
          title="设为封面">
          <i class="ivu-icon ivu-icon-android-bookmark"
            :class="item.isCover == '1' ? 'actived' : ''"></i>
          <p>封</p>
        </div>
        <div class="list-img-remark" v-if="hasRemark">
          <Input placeholder="请输入评测" v-if="mark" v-model="item.description"
            @on-blur="handleSetReamrk(index, item)" clearable></Input>
          <span v-if="!mark"> {{item.description}} </span>
        </div>
      </div>
      <div slot="footer" class="addBox">

        <div class="boxUpload" v-if="imgList.length==0 && isboxUpload">图片显示<br><span
            v-if="panduanwenzi">{{size}}</span></div>
        <div class="upload" id="uploadId1" v-if="mark && ( num == 0 || num > imgList.length)">
          <!-- <Button class="uploadButton" icon="ios-cloud-upload-outline">
            <input  type="file" id="fileUpload"  accept="image/png,image/jpg,image/jpeg" @change="fileChange($event)">上传图片
          </Button> -->
          <Upload :action="upload.reqUrl" :headers='upload.headers' :data="upload.data"
            :on-error="unloadError" :on-success="imgUnloadSuccess" name="multipartFile">
            <Button icon="ios-cloud-upload-outline">上传图片</Button>
          </Upload>
          <div class="upload-type" v-if="jindu && isboxUpload">
            <label class="status">状态: <span>{{statusText}}</span></label>
            <span class="progress">进度: <i id="auth-progress">{{authProgress}}</i> %</span>
          </div>
        </div>
      </div>
    </draggable>

    <preview-image ref="previewImage" :images="preview.images" :showDownLoad="true"
      :showIndex="preview.showIndex" />
  </div>
</template>

<script>
  import draggable from 'vuedraggable'
  import encryptList from '@/common/secret.js'
  import toolMgr from "@/biz/base/tool.js";
  export default {
    components: {
      draggable,
    },
    props: {
      num: {
        type: Number,
        default: 0,
      },
      flags: {
        type: Number,
      },
      isPhotoAlbum: {
        type: Boolean,
        default: true,
      },
      hasNoWatermark: {
        type: Boolean,
        default: false,
      },
      mark: {
        type: Boolean,
        default: true,
      },
      hasDrag: {
        type: Boolean,
        default: false,
      },
      deleteFun: {
        type: Boolean,
        default: false,
      },
      size: {
        type: String,
        default: '尺寸大小750x422',
      },
      hasCover: {
        type: Boolean,
        default: false,
      },
      hasRemark: {
        type: Boolean,
        default: false,
      },
      panduanwenzi: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        loudongimg: {
          width: null,
          height: null,
        },

        upload: toolMgr.unloadImage(),

        jindu: false,
        videoIds: null,
        isboxUpload: true,
        viewImageUrl: '',
        timeout: '',
        partSize: '',
        parallel: '',
        retryCount: '',
        retryDuration: '',
        region: 'cn-shanghai',
        userId: '1887964317723133',
        file: null,
        authProgress: 0,
        uploadDisabled: true,
        resumeDisabled: true,
        pauseDisabled: true,
        uploader: null,
        statusText: '',
        logSource: null,
        defaultList: [],
        getToken: '',
        imgName: '',
        updata: {
          fileName: '',
        },
        imgList: [],
        thumbnailList: [],
        preview: {
          images: [],
          showIndex: 0
        },
      }
    },
    methods: {
      isboxUploadshow() {
        this.isboxUpload = false
      },
      //图片上传成功回调
      imgUnloadSuccess(response, file, fileList) {
        let data = encryptList.Decrypt(response.data)
        data = data
        let isCover = 0
        if (this.hasCover && this.imgList.length === 0) {
          isCover = 1
        }
        this.imgList.push({
          annexPath: data.imageURL,
          isCover: isCover,
        })
        console.log(data.imageURL)
        this.updateImgList(data.imageURL)
      },
      //将回调父组件的方法
      updateImgList(imgList) {
        let parms = {
          imgList: imgList,
          flags: this.flags,
        }
        this.$emit('handleSuccess', parms)
      },
      //图片上传失败回调
      unloadError(error, file, fileList) {
        console.log(1111, error, file, fileList)
      },

      fileChange(e) {
        console.log(656565)
        var that = this
        // 单张上传
        that.file = e.target.files[0]
        if (that.file.size > 1024 * 1024 * 5) {
          that.$Message.error('上传图片不能大于5M')
          return
        }
        var newdate = new FormData()
        newdate.append('title', '1111')
        newdate.append('appName', 'web_back')
        newdate.append('appVersion', '1.0')
        newdate.append('multipartFile', that.file)
        var Title = that.file.name

        // var restApi = Api.user.getAliImg+'?title='+Title
        var restApi = Base.uploadImage + '?title=' + Title
        if (this.hasNoWatermark) {
          restApi = Base.uploadImageNoWaterMark + '?title=' + Title
        }

        //Helper.globalLoading_show();
        Rest.upload(restApi, newdate).done(function(res) {
          if (Helper.isSuccess(res)) {
            if (res) {
              document.getElementById('fileUpload').value = null
              let dataJson = secret.Decrypt(res.data)
              that.jindu = true
              that.statusText = '上传成功'
              that.authProgress = '100'
              that.handleSuccess(dataJson)
            } else {}
          } else {
            that.$Message.error(res.status.msg)
          }
        })
        // Helper.globalLoading_hide();
        return
      },
      authUpload() {
        // 然后调用 startUpload 方法, 开始上传
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.uploadDisabled = true
          this.pauseDisabled = false
        }
      },
      // 暂停上传
      pauseUpload() {
        if (this.uploader !== null) {
          this.uploader.stopUpload()
          this.resumeDisabled = false
          this.pauseDisabled = true
        }
      },
      // 恢复上传
      resumeUpload() {
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.resumeDisabled = true
          this.pauseDisabled = false
        }
      },
      changeRadio(value, item) {
        var that = this
        return
        if (Helper.getSearchItem('flage') == 'add') {
          var currentStatus = this.flags
          switch (currentStatus) {
            case '1':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccessone', that.imgList)
              break
            case '2':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccesstwo', that.imgList)
              break
            case '3':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccessthree', that.imgList)
              break
            case '4':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccessfour', that.imgList)
              break
            case '5':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccessfive', that.imgList)
              break
            case '7':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccessseven', that.imgList)
              break
            case '8':
              for (var i = 0; i < that.imgList.length; i++) {
                that.imgList[i].isCover = 0
                if (value == i) {
                  that.imgList[value].isCover = 1
                }
              }
              that.$emit('handleSuccesseight', that.imgList)
              break
          }
        } else {
          that.homePicture(item.id)
        }
        // alert($('input[name="testradio"]:eq('+value+')').val())
        // alert(value)
      },
      // 设置为封面图(新增时不调用，编辑时调用)
      homePicture(ids) {
        var that = this
        var params = {
          id: ids,
          logSource: that.logSource,
        }
        return
        if (ids != undefined && ids > 0) {
          Helper.globalLoading_show()
          var restApi = Api.caseManage.albumphote.homePicture
          Rest.get(restApi, params).done((res) => {
            if (Helper.isSuccess(res)) {
              that.$Message.success(res.status.msg)
            } else {
              if (res.status && res.status.msg) {
                that.$Message.error(res.status.msg)
              }
            }
            Helper.globalLoading_hide()
          })
        }
      },
      //验证图片类型展示不同的图片
      testFileType() {
        //上传图片和文件
      },
      handleSetReamrk(index, item) {
        console.log(this.imgList)
        console.log(item)
        console.log('输入框')
        console.log(index)
        if (this.hasRemark) {
          this.updateImgList()
        }
        // this.imgList.splice(index, 1);
        // console.log('====删除后的 list ======')
        // console.log(this.imgList);
      },
      handleRemove(index, item) {
        console.log(this.imgList, item)
        this.$Modal.confirm({
          width: '300px',
          content: '<p style="margin-left: -50px;">你确认要删除该图片吗？</p>',
          onOk: () => {
            console.log(this.deleteFun, this.isPhotoAlbum, '11111111')
            if (this.deleteFun) {
              this.imgList.splice(index, 1)
              this.$emit('delFun', item)
              // if (!this.isPhotoAlbum) {
              //   this.imgList.splice(index, 1)
              //   this.$emit('delFun', item)
              // } else {
              //   getIntroduceDelete({
              //     buildingId: this.$route.query.bid,
              //     introduceId: item.introduceId,
              //   }).then((res) => {
              //     this.$Message.success('删除成功')
              //     this.imgList.splice(index, 1)
              //   })
              // }
            } else {
              this.updateImgList()
            }
          },
          onCancel: () => {},
        })
        this.jindu = false
      },
      // 设为封面
      handleSetCover(index, item) {
        // 设置数组中所有的为非封面
        if (this.mark) {
          this.imgList.forEach(function(item) {
            console.log(item)
            item.isCover = 0
          })
          item.isCover = 1
          console.log(this.imgList)
          this.updateImgList()
        }
      },
      // updateImgList() {
      //   let parms = {
      //     imgList: this.imgList,
      //     flags: this.flags
      //   }
      //   this.$emit('handleSuccess', parms);
      // },
      handleSuccess(res) {
        console.log('上传完成后===================')
        console.log(this.flags)
        console.log(res)
        let isCover = 0
        if (this.hasCover && this.imgList.length === 0) {
          isCover = 1
        }
        this.imgList.push({
          annexPath: res.imageURL,
          isCover: isCover,
        })
        console.log(this.imgList)
        this.updateImgList()
      },
      drop() {
        let parms = {
          imgList: this.imgList,
          flags: this.flags,
        }
        this.$emit('dropFun', parms)
        console.log('==========================拖拽================')
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: '不支持此类型的文件',
          desc: 'file' + file.name + ' 请选择jpg or png.',
        })
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: '图片大小不能超过10M',
          desc: 'File  ' + file.name + ' is too large, no more than 10M.',
        })
      },
      handleBeforeUpload() {
        var that = this

        function getFileName(o) {
          var pos = o.lastIndexOf('\\')
          return o.substring(pos + 1)
        }
        if (that.flags == '1') {
          var filees = $('#uploadId1 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '2') {
          var filees = $('#uploadId2 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '3') {
          var filees = $('#uploadId3 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '4') {
          var filees = $('#uploadId4 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '5') {
          var filees = $('#uploadId5 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '7') {
          var filees = $('#uploadId7 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        } else if (that.flags == '8') {
          var filees = $('#uploadId8 input').val()
          var fileNames = getFileName(filees)
          this.updata.fileName = fileNames
        }

        const check = this.imgList.length < 5
      },
      onPreview(index) {
        this.preview.images = this.imgList.map(i => (i.annexPath))
        this.preview.showIndex = index
        this.$refs.previewImage.show()
      },
      viewPdf(pdfLink) {
        // console.log(pdfLink)
        window.open(pdfLink)
      },
    },
    watch: {
      mark(newval) {
        this.mark = newval
      },
    },
    mounted() {
      var that = this
      that.jindu = false
      //.get('token');
      //that.logSource = Helper.getSearchItem('logSource');
    },
    created() {
      var that = this
      that.jindu = false
    },
    activated() {
      var that = this
      that.jindu = false
    },
  }
</script>
<style lang="scss" scoped>
  @import '../assets/sass/install';

  .boxUpload {
    width: 160px;
    height: 160px;
    border: solid 1px #ccc;
    line-height: 50px;
    padding-top: 30px;
    margin: 10px 10px 10px 0;
    text-align: center;
  }

  .img-contain {
    margin-right: 80px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;

    .img-list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .demo-upload-list:hover .demo-upload-list-cover {
      display: block;
    }

    .addBox {
      display: flex;
      align-items: center;
    }

    .demo-upload-list {
      display: inline-block;
      width: 160px;
      text-align: center;
      background: #fff;
      position: relative;
      margin: 10px 10px 10px 0;
      overflow: hidden;

      img {
        display: block;
        width: 160px;
        height: 160px;
        border: 1px solid #eeeeee;
      }

      .img {
        display: block;
        width: 160px;
        height: 160px;
        object-fit: cover;
        border-radius: 8px;
      }

      .list-img-remark {
        margin: 5px 0px;
        width: 160px;
        text-align: left;
      }

      span {
        text-align: left;
        line-height: 20px;
      }

      .list-cover-marker {
        position: absolute;
        right: 0px;
        top: -5px;
        line-height: 0;

        i {
          color: #b5b5b5;
          font-size: 50px;
        }

        i.actived {
          color: #56c1ea;
        }

        p {
          position: absolute;
          right: 2px;
          top: 22px;
          font-size: 22px;
          cursor: pointer;
          color: #ffffff;
          z-index: 999999;
          font-family: 黑体;
        }
      }

      .demo-upload-list-cover {
        width: 160px;
        height: 160px;
        display: none;
        position: absolute;
        line-height: 160px;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 8px;

        i {
          color: #fff;
          font-size: 20px;
          cursor: pointer;
          margin: 0 5px;
        }

        .coverIcon {}

        .actived {
          color: #56c1ea;
        }

        .radio-l {
          label {
            position: relative;
            top: 0px;
            // color: #B7BABB;
            line-height: 16px;
          }
        }
      }
    }
  }

  .uploadButton {
    display: block;
    width: 150px;
    height: 40px;
  }

  .upload {
    /*position: absolute;*/
    /*top: 90px;*/
    /*left:190px;*/
    margin: 0 20px;
  }

  .boxInput {
    position: absolute;
    display: block;
    width: 150px;
    height: 40px;
    top: 0px;
    left: 0px;
    opacity: 0;
  }

  .deleteImg {
    display: inline-block;
    opacity: 1;
    width: 17px;
    height: 17px;
    background: url(../assets/images/delete.png) no-repeat;

    &:hover {
      display: inline-block;
      opacity: 1;
      width: 17px;
      height: 17px;
      background: url(../assets/images/delete-active.png) no-repeat;
      background-size: 17px 17px;
    }
  }
</style>